<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能对话测试页面</title>
    
    <!-- Marked.js - Markdown解析 -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <!-- Highlight.js - 代码高亮 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github-dark.min.css">
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/highlight.min.js"></script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 900px;
            height: 90vh;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .header .info {
            font-size: 14px;
            opacity: 0.9;
        }

        .config-panel {
            background: #f8f9fa;
            padding: 15px 30px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            gap: 20px;
            align-items: center;
            flex-wrap: wrap;
        }

        .config-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .config-item label {
            font-size: 14px;
            color: #666;
        }

        .config-item input {
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            width: 100px;
        }

        .btn-clear {
            padding: 8px 20px;
            background: #ff6b6b;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-clear:hover {
            background: #ff5252;
            transform: translateY(-2px);
        }

        .chat-area {
            flex: 1;
            overflow-y: auto;
            padding: 30px;
            background: #fafafa;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            justify-content: flex-end;
        }

        .message.assistant {
            justify-content: flex-start;
        }

        .message-content {
            max-width: 70%;
            padding: 15px 20px;
            border-radius: 15px;
            position: relative;
            word-wrap: break-word;
            line-height: 1.6;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 5px;
        }

        .message.assistant .message-content {
            background: white;
            color: #333;
            border-bottom-left-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        /* Markdown样式 */
        .message-content h1, .message-content h2, .message-content h3 {
            margin-top: 16px;
            margin-bottom: 8px;
            font-weight: 600;
        }
        
        .message-content h1 { font-size: 1.5em; }
        .message-content h2 { font-size: 1.3em; }
        .message-content h3 { font-size: 1.1em; }
        
        .message-content p {
            margin-bottom: 8px;
        }
        
        .message-content code {
            background: #f6f8fa;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 0.9em;
        }
        
        .message.user .message-content code {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .message-content pre {
            background: #1e1e1e;
            padding: 12px;
            border-radius: 6px;
            overflow-x: auto;
            margin: 8px 0;
        }
        
        .message-content pre code {
            background: transparent;
            padding: 0;
            color: #e6e6e6;
        }
        
        .message-content ul, .message-content ol {
            margin-left: 20px;
            margin-bottom: 8px;
        }
        
        .message-content li {
            margin-bottom: 4px;
        }
        
        .message-content blockquote {
            border-left: 4px solid #667eea;
            padding-left: 12px;
            margin: 8px 0;
            color: #666;
        }
        
        .message-content strong {
            font-weight: 600;
        }
        
        .message-content em {
            font-style: italic;
        }
        
        .message-content a {
            color: #667eea;
            text-decoration: none;
        }
        
        .message-content a:hover {
            text-decoration: underline;
        }
        
        .message-content table {
            border-collapse: collapse;
            margin: 8px 0;
            width: 100%;
        }
        
        .message-content table th,
        .message-content table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        
        .message-content table th {
            background: #f6f8fa;
            font-weight: 600;
        }
        
        .message-content hr {
            border: none;
            border-top: 1px solid #ddd;
            margin: 12px 0;
        }

        .message-time {
            font-size: 12px;
            opacity: 0.7;
            margin-top: 5px;
        }

        .message.user .message-time {
            text-align: right;
        }

        .loading {
            display: flex;
            gap: 5px;
            padding: 10px;
        }

        .loading-dot {
            width: 8px;
            height: 8px;
            background: #667eea;
            border-radius: 50%;
            animation: bounce 1.4s infinite ease-in-out;
        }

        .loading-dot:nth-child(1) {
            animation-delay: -0.32s;
        }

        .loading-dot:nth-child(2) {
            animation-delay: -0.16s;
        }

        @keyframes bounce {
            0%, 80%, 100% {
                transform: scale(0);
            }
            40% {
                transform: scale(1);
            }
        }

        .input-area {
            padding: 20px 30px;
            background: white;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 15px;
        }

        .input-box {
            flex: 1;
            display: flex;
            background: #f5f5f5;
            border-radius: 25px;
            padding: 5px 20px;
            align-items: center;
        }

        .input-box input {
            flex: 1;
            border: none;
            background: transparent;
            padding: 10px;
            font-size: 15px;
            outline: none;
        }

        .btn-send {
            padding: 12px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.3s;
            min-width: 100px;
        }

        .btn-send:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-send:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .welcome {
            text-align: center;
            padding: 50px 20px;
            color: #999;
        }

        .welcome h2 {
            font-size: 24px;
            margin-bottom: 10px;
            color: #667eea;
        }

        .welcome p {
            font-size: 16px;
            line-height: 1.8;
        }

        .quick-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
            flex-wrap: wrap;
            justify-content: center;
        }

        .quick-btn {
            padding: 10px 20px;
            background: white;
            border: 2px solid #667eea;
            color: #667eea;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .quick-btn:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
        }

        .status {
            padding: 10px 20px;
            background: #e8f5e9;
            color: #2e7d32;
            border-radius: 10px;
            font-size: 14px;
            margin: 10px 30px;
        }

        .status.error {
            background: #ffebee;
            color: #c62828;
        }

        /* 滚动条样式 */
        .chat-area::-webkit-scrollbar {
            width: 8px;
        }

        .chat-area::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .chat-area::-webkit-scrollbar-thumb {
            background: #667eea;
            border-radius: 4px;
        }

        .chat-area::-webkit-scrollbar-thumb:hover {
            background: #5568d3;
        }

        /* 打字光标效果 */
        .typing-cursor {
            display: inline-block;
            width: 2px;
            height: 1em;
            background-color: #667eea;
            margin-left: 2px;
            animation: blink 1s infinite;
            vertical-align: text-bottom;
        }

        @keyframes blink {
            0%, 49% {
                opacity: 1;
            }
            50%, 100% {
                opacity: 0;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <h1>🤖 AI智能对话测试</h1>
            <div class="info">基于智谱GLM-4</div>
        </div>

        <!-- 配置面板 -->
        <div class="config-panel">
            <div class="config-item">
                <label>用户ID:</label>
                <input type="number" id="userId" value="1">
            </div>
            <div class="config-item">
                <label>会话ID:</label>
                <input type="text" id="sessionId" placeholder="自动生成" readonly>
            </div>
            <button class="btn-clear" onclick="clearChat()">清除对话</button>
        </div>

        <!-- 状态提示 -->
        <div id="status" style="display: none;"></div>

        <!-- 聊天区域 -->
        <div class="chat-area" id="chatArea">
            <div class="welcome">
                <h2>👋 欢迎使用AI智能助手</h2>
                <p>我是基于智谱GLM-4的智能阅读助手<br>可以帮助您分析、总结和理解内容</p>
                <div class="quick-actions">
                    <button class="quick-btn" onclick="sendQuickMessage('介绍一下你自己')">介绍一下你自己</button>
                    <button class="quick-btn" onclick="sendQuickMessage('总结《红楼梦》的主要内容')">总结红楼梦</button>
                    <button class="quick-btn" onclick="sendQuickMessage('如何提高阅读效率？')">阅读技巧</button>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
            <div class="input-box">
                <input type="text" id="messageInput" placeholder="输入您的问题..." onkeypress="handleKeyPress(event)">
            </div>
            <button class="btn-send" id="sendBtn" onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script>
        let isLoading = false;
        let sessionId = null;

        // 发送消息（流式）
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message || isLoading) return;
            
            // 清空输入框
            input.value = '';
            
            // 添加用户消息
            addMessage('user', message);
            
            // 显示加载状态
            isLoading = true;
            updateSendButton();
            showLoading();
            
            try {
                const userId = document.getElementById('userId').value || 1;
                
                const response = await fetch('/api/v1/chat/send/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        userId: parseInt(userId),
                        sessionId: sessionId,
                        message: message
                    })
                });
                
                // 读取流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullReply = '';
                let buffer = ''; // 用于累积不完整的行
                let aiMessageDiv = null;
                let textSpan = null;
                let firstContentReceived = false;
                
                while (true) {
                    const {done, value} = await reader.read();
                    if (done) break;
                    
                    // 解码并添加到缓冲区
                    const chunk = decoder.decode(value, {stream: true});
                    buffer += chunk;
                    
                    // 按换行符分割
                    const lines = buffer.split('\n');
                    
                    // 保留最后一个可能不完整的行
                    buffer = lines.pop() || '';
                    
                    // 处理完整的行
                    for (const line of lines) {
                        const trimmedLine = line.trim();
                        if (!trimmedLine) continue; // 跳过空行
                        
                        if (trimmedLine.startsWith('data:')) {
                            try {
                                const jsonStr = trimmedLine.substring(5).trim();
                                if (!jsonStr) continue;
                                
                                const data = JSON.parse(jsonStr);
                                
                                if (data.type === 'session') {
                                    sessionId = data.sessionId;
                                    document.getElementById('sessionId').value = sessionId;
                                } else if (data.type === 'content') {
                                    // 第一次收到内容时，移除加载动画并创建消息容器
                                    if (!firstContentReceived) {
                                        removeLoading();
                                        aiMessageDiv = createMessageElement('assistant');
                                        textSpan = aiMessageDiv.querySelector('span');
                                        firstContentReceived = true;
                                    }
                                    
                                    fullReply += data.content;
                                    // 渲染Markdown并添加光标
                                    const cursor = textSpan.querySelector('.typing-cursor');
                                    if (cursor) cursor.remove();
                                    
                                    // 使用marked渲染Markdown
                                    const htmlContent = marked.parse(fullReply);
                                    textSpan.innerHTML = htmlContent;
                                    
                                    // 代码高亮
                                    textSpan.querySelectorAll('pre code').forEach((block) => {
                                        hljs.highlightElement(block);
                                    });
                                    
                                    // 添加光标
                                    const cursorSpan = document.createElement('span');
                                    cursorSpan.className = 'typing-cursor';
                                    textSpan.appendChild(cursorSpan);
                                    // 自动滚动
                                    const chatArea = document.getElementById('chatArea');
                                    chatArea.scrollTop = chatArea.scrollHeight;
                                } else if (data.type === 'done') {
                                    // 移除光标并最后渲染一次
                                    if (textSpan) {
                                        const cursor = textSpan.querySelector('.typing-cursor');
                                        if (cursor) cursor.remove();
                                        
                                        // 最终渲染
                                        const htmlContent = marked.parse(fullReply);
                                        textSpan.innerHTML = htmlContent;
                                        
                                        // 代码高亮
                                        textSpan.querySelectorAll('pre code').forEach((block) => {
                                            hljs.highlightElement(block);
                                        });
                                    }
                                    showStatus('✅ 回复完成', 'success');
                                } else if (data.type === 'error') {
                                    showStatus('❌ ' + data.message, 'error');
                                }
                            } catch (e) {
                                console.warn('解析SSE数据失败:', trimmedLine, e);
                            }
                        }
                    }
                }
                
            } catch (error) {
                console.error('发送失败:', error);
                removeLoading();
                addMessage('assistant', '抱歉，网络连接失败，请检查服务是否正常运行。');
                showStatus('❌ 网络错误: ' + error.message, 'error');
            } finally {
                isLoading = false;
                updateSendButton();
            }
        }
        
        // 创建消息元素
        function createMessageElement(role) {
            const chatArea = document.getElementById('chatArea');
            
            // 移除欢迎消息
            const welcome = chatArea.querySelector('.welcome');
            if (welcome) {
                welcome.remove();
            }
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            
            const now = new Date();
            const time = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            
            const textSpan = document.createElement('span');
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            timeDiv.textContent = time;
            
            contentDiv.appendChild(textSpan);
            contentDiv.appendChild(timeDiv);
            messageDiv.appendChild(contentDiv);
            chatArea.appendChild(messageDiv);
            
            // 滚动到底部
            chatArea.scrollTop = chatArea.scrollHeight;
            
            return messageDiv;
        }
        
        // 快速发送消息
        function sendQuickMessage(message) {
            document.getElementById('messageInput').value = message;
            sendMessage();
        }
        
        // 添加消息到聊天区域
        function addMessage(role, content) {
            const chatArea = document.getElementById('chatArea');
            
            // 移除欢迎消息
            const welcome = chatArea.querySelector('.welcome');
            if (welcome) {
                welcome.remove();
            }
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            
            const now = new Date();
            const time = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            
            const textSpan = document.createElement('span');
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            timeDiv.textContent = time;
            
            // 渲染Markdown
            const htmlContent = marked.parse(content);
            textSpan.innerHTML = htmlContent;
            
            // 代码高亮
            textSpan.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightElement(block);
            });
            
            contentDiv.appendChild(textSpan);
            contentDiv.appendChild(timeDiv);
            messageDiv.appendChild(contentDiv);
            chatArea.appendChild(messageDiv);
            
            // 滚动到底部
            chatArea.scrollTop = chatArea.scrollHeight;
        }
        
        // 打字机效果
        function typeWriter(element, text, index) {
            // 移除之前的光标
            const oldCursor = element.querySelector('.typing-cursor');
            if (oldCursor) {
                oldCursor.remove();
            }
            
            if (index < text.length) {
                const char = text.charAt(index);
                
                // 处理换行符
                if (char === '\n') {
                    element.innerHTML += '<br>';
                } else {
                    element.innerHTML += char;
                }
                
                // 添加光标
                const cursor = document.createElement('span');
                cursor.className = 'typing-cursor';
                element.appendChild(cursor);
                
                // 自动滚动
                const chatArea = document.getElementById('chatArea');
                chatArea.scrollTop = chatArea.scrollHeight;
                
                // 根据字符类型调整速度
                let delay = 30; // 默认30ms
                
                // 如果是标点符号，稍作停顿
                if ('，。！？；：、'.includes(char)) {
                    delay = 150;
                } else if (',.!?;:'.includes(char)) {
                    delay = 150;
                } else if (char === '\n') {
                    delay = 100;
                }
                
                setTimeout(() => typeWriter(element, text, index + 1), delay);
            } else {
                // 打字完成，移除光标
                const cursor = element.querySelector('.typing-cursor');
                if (cursor) {
                    cursor.remove();
                }
            }
        }
        
        // 显示加载动画
        function showLoading() {
            const chatArea = document.getElementById('chatArea');
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'message assistant';
            loadingDiv.id = 'loadingMessage';
            loadingDiv.innerHTML = `
                <div class="message-content">
                    <div class="loading">
                        <div class="loading-dot"></div>
                        <div class="loading-dot"></div>
                        <div class="loading-dot"></div>
                    </div>
                </div>
            `;
            chatArea.appendChild(loadingDiv);
            chatArea.scrollTop = chatArea.scrollHeight;
        }
        
        // 移除加载动画
        function removeLoading() {
            const loading = document.getElementById('loadingMessage');
            if (loading) {
                loading.remove();
            }
        }
        
        // 更新发送按钮状态
        function updateSendButton() {
            const btn = document.getElementById('sendBtn');
            btn.disabled = isLoading;
            btn.textContent = isLoading ? '发送中...' : '发送';
        }
        
        // 显示状态提示
        function showStatus(message, type) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = 'status ' + (type === 'error' ? 'error' : '');
            status.style.display = 'block';
            
            setTimeout(() => {
                status.style.display = 'none';
            }, 3000);
        }
        
        // 清除对话
        async function clearChat() {
            if (!confirm('确定要清除所有对话记录吗？')) {
                return;
            }
            
            const userId = document.getElementById('userId').value || 1;
            
            // 如果有会话ID，调用后端清除
            if (sessionId) {
                try {
                    await fetch(`/api/v1/chat/clear/${sessionId}?userId=${userId}`, {
                        method: 'DELETE'
                    });
                } catch (error) {
                    console.error('清除会话失败:', error);
                }
            }
            
            // 清除本地显示
            const chatArea = document.getElementById('chatArea');
            chatArea.innerHTML = `
                <div class="welcome">
                    <h2>👋 欢迎使用AI智能助手</h2>
                    <p>我是基于智谱GLM-4的智能阅读助手<br>可以帮助您分析、总结和理解内容</p>
                    <div class="quick-actions">
                        <button class="quick-btn" onclick="sendQuickMessage('介绍一下你自己')">介绍一下你自己</button>
                        <button class="quick-btn" onclick="sendQuickMessage('总结《红楼梦》的主要内容')">总结红楼梦</button>
                        <button class="quick-btn" onclick="sendQuickMessage('如何提高阅读效率？')">阅读技巧</button>
                    </div>
                </div>
            `;
            
            // 重置会话ID
            sessionId = null;
            document.getElementById('sessionId').value = '';
            
            showStatus('✅ 对话已清除', 'success');
        }
        
        // 回车发送
        function handleKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }
        
        // 页面加载完成
        window.onload = function() {
            document.getElementById('messageInput').focus();
            showStatus('✅ 测试页面加载成功，请输入消息开始对话', 'success');
        };
    </script>
</body>
</html>

